"use strict";

const Controller = require("egg").Controller;

class HomeController extends Controller {
  async index() {
    const { ctx } = this;
    ctx.body = "hi, egg";
  }
  // 数据
  async list() {
    const { ctx } = this;
    const { pageindex, pagesize } = ctx.query;
    // pageindex 下标为-1
    const results = `SELECT * FROM shops limit ${pageindex - 1},${pagesize}`;
    const result = await this.app.mysql.select("shops");
    const data = await this.app.mysql.query(results);
    ctx.body = {
      data: data,
      //总长度
      total: result.length,
    };
  }
  // 添加

  async add() {
    const { ctx, app } = this;
    const { name, region, price, time, sort } = ctx.query;
    const result = await app.mysql.insert("shops", {
      name: name,
      region: region,
      price: price,
      time: time,
      sort: sort,
    });
    ctx.body = result;
  }

  // 删除
  async del() {
    const { ctx, app } = this;
    const { id } = ctx.params;
    const result = await app.mysql.delete("shops", {
      id: id,
    });
    ctx.body = result;
  }
  // 编辑
  async edit() {
    const { ctx, app } = this;
    const { name, region, price, sort, id } = ctx.query;
    const result = await app.mysql.update("shops", {
      id: id,
      name: name,
      region: region,
      price: price,
      sort: sort,
    });
    ctx.body = result;
  }
  // 搜索
  async search() {
    const { ctx, app } = this;
    const { name } = ctx.query;
    let sql = " select * from shops where 1 ";
    if (name) {
      sql += ` and name like "%${name}%" `;
    }
    const result = await app.mysql.query(sql);
    ctx.body = result;
  }
}

module.exports = HomeController;
